<template>
  <div class="found-page">
    <div class="page-header">
      <h2>失物招领</h2>
      <el-button type="primary" @click="$router.push('/publish?type=found')">
        <el-icon><Plus /></el-icon>发布招领信息
      </el-button>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="物品类别">
          <el-select
            v-model="filters.category"
            placeholder="全部类别"
            clearable
            @change="handleFilterChange"
            style="width: 180px"
          >
            <el-option
              v-for="cat in categories"
              :key="cat.id"
              :label="cat.name"
              :value="cat.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="拾获时间">
          <el-date-picker
            v-model="filters.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleTimeChange"
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索物品名称/描述"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表内容 -->
    <div class="items-list">
      <el-row :gutter="20">
        <el-col :span="6" v-for="item in displayItems" :key="item.id">
          <el-card :body-style="{ padding: '0px' }" class="item-card">
            <div
              class="item-image"
              :style="{ backgroundImage: `url(${item.image})` }"
            >
              <div class="item-status" :class="item.status">
                {{ item.statusText }}
              </div>
            </div>
            <div class="item-content">
              <h3>{{ item.name }}</h3>
              <div class="item-info">
                <p>
                  <el-icon><Timer /></el-icon>
                  <span>{{ item.foundTime }}</span>
                </p>
                <p>
                  <el-icon><Location /></el-icon>
                  <span>{{ item.location }}</span>
                </p>
              </div>
              <div class="item-description">{{ item.description }}</div>
              <div class="item-footer">
                <el-tag size="small" :type="item.category.type">
                  {{ item.category.name }}
                </el-tag>
                <el-button type="primary" link @click="showDetail(item)">
                  查看详情
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 36, 48]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import api from "@/utils/api";
import { Plus, Timer, Location } from "@element-plus/icons-vue";

export default {
  name: "FoundPage",
  components: {
    Plus,
    Timer,
    Location,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const loading = ref(false);
    const items = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(12);
    const categories = ref([]);

    // 定义表单筛选条件
    const filters = reactive({
      category: null,
      timeRange: null,
      keyword: "",
    });

    // 筛选参数 (实际API请求参数)
    const filterData = reactive({
      type: "found", // 固定为失物招领类型
      keyword: "",
      category: null,
      timeStart: "",
      timeEnd: "",
      page: 1,
      pageSize: 12,
    });

    // 处理筛选时间
    const handleTimeChange = () => {
      if (filters.timeRange && filters.timeRange.length === 2) {
        filterData.timeStart = filters.timeRange[0];
        filterData.timeEnd = filters.timeRange[1];
      } else {
        filterData.timeStart = "";
        filterData.timeEnd = "";
      }
      handleFilterChange();
    };

    // 处理搜索
    const handleSearch = () => {
      console.log(
        "搜索前 filters.category:",
        filters.category,
        typeof filters.category
      );
      // 同步表单筛选条件到API参数
      filterData.keyword = filters.keyword;
      
      // 如果类别有值，则使用该值；如果没有值，则使用 null
      filterData.category =
        filters.category !== null && filters.category !== undefined
          ? filters.category
          : null;
          
      filterData.page = 1; // 重置到第一页
      fetchItems();
    };

    // 重置筛选条件
    const resetFilters = () => {
      filters.category = null;
      filters.timeRange = null;
      filters.keyword = "";
      filterData.keyword = "";
      filterData.category = null;
      filterData.timeStart = "";
      filterData.timeEnd = "";
      handleSearch();
    };

    // 处理筛选条件变化
    const handleFilterChange = () => {
      console.log("筛选条件变更:", filters.category, typeof filters.category);
      handleSearch();
    };

    // 获取分类数据
    const fetchCategories = async () => {
      try {
        const response = await api.get("/categories");
        if (response.data.code === 200) {
          categories.value = (response.data.data || []).map((cat) => ({
            ...cat,
            id: Number(cat.id),
          }));
          console.log("加载的分类数据:", categories.value);
        }
      } catch (error) {
        ElMessage.warning("获取分类数据失败，使用默认分类");
        // 使用默认分类
        categories.value = [
          { id: 1, name: "证件卡类" },
          { id: 2, name: "电子设备" },
          { id: 3, name: "书籍资料" },
          { id: 4, name: "生活用品" },
          { id: 5, name: "随身物品" },
          { id: 6, name: "其他物品" },
        ];
        console.log("使用默认分类:", categories.value);
      }
      
      // 打印当前选中的分类值
      console.log("当前选中的分类:", filters.category);
    };

    // 获取物品数据
    const fetchItems = async () => {
      console.log("API请求参数:", filterData);
      loading.value = true;
      try {
        const response = await api.get("/items", { params: filterData });
        if (response.data.code === 200) {
          items.value = response.data.data.list || [];
          total.value = response.data.data.total || 0;
        } else {
          ElMessage.warning("获取数据失败: " + response.data.message);
          loadMockData();
        }
      } catch (error) {
        console.error("获取失物招领数据失败:", error);
        ElMessage.warning("网络错误，加载示例数据");
        loadMockData();
      } finally {
        loading.value = false;
      }
    };

    // 加载模拟数据
    const loadMockData = () => {
      items.value = [
        {
          id: "FOUND-202306150001",
          name: "蓝色水杯",
          categoryId: 4,
          categoryName: "生活用品",
          time: "2023-06-15 14:30",
          location: "教学楼A栋",
          description: "蓝色保温杯，有校徽标志",
          storage: "失物招领处",
          images: ["https://example.com/images/bottle1.jpg"],
          contact: "138****8000",
          status: 1
        },
        {
          id: "FOUND-202306150002",
          name: "学生证",
          categoryId: 1,
          categoryName: "证件卡类",
          time: "2023-06-16 09:15",
          location: "图书馆二楼",
          description: "计算机学院学生证，姓名已隐去",
          storage: "图书馆服务台",
          images: ["https://example.com/images/card1.jpg"],
          contact: "139****7777",
          status: 1
        },
        {
          id: "FOUND-202306150003",
          name: "黑色钱包",
          categoryId: 5,
          categoryName: "随身物品",
          time: "2023-06-17 16:20",
          location: "食堂一楼",
          description: "黑色真皮钱包，内有少量现金",
          storage: "学生会办公室",
          images: ["https://example.com/images/wallet1.jpg"],
          contact: "132****5555",
          status: 1
        },
        {
          id: "FOUND-202306150004",
          name: "平板电脑",
          categoryId: 2,
          categoryName: "电子设备",
          time: "2023-06-18 11:30",
          location: "操场",
          description: "白色平板电脑，无密码",
          storage: "保卫处",
          images: ["https://example.com/images/tablet1.jpg"],
          contact: "138****3333",
          status: 1
        },
      ];
      total.value = items.value.length;
    };

    // 转换数据格式以适应前端展示
    const displayItems = computed(() => {
      if (!items.value || items.value.length === 0) return [];

      return items.value
        .filter(item => item && item.categoryId && item.categoryName) // 添加过滤条件
        .map((item) => ({
          id: item.id,
          name: item.name,
          image:
            item.images && item.images.length > 0
              ? item.images[0]
              : "https://img.shetu66.com/2023/08/02/1690966649671884.png",
          description: item.description,
          foundTime: item.time.split(" ")[0], // 只取日期部分
          location: Array.isArray(item.location)
            ? item.location.join("-")
            : item.location,
          status: item.status === 1 ? "found" : "returned",
          statusText: item.status === 1 ? "招领中" : "已归还",
          storage: item.storage,
          category: {
            id: item.categoryId,
            name: item.categoryName,
            type: getCategoryType(item.categoryId),
          },
          contact: item.contact,
        }));
    });

    // 根据分类ID获取分类的展示类型
    const getCategoryType = (categoryId) => {
      const types = ['danger', 'primary', 'info', 'success', 'warning'];
      return types[(categoryId % types.length)];
    };

    // 显示详情
    const showDetail = (item) => {
      router.push(`/found/${item.id}`);
    };

    // 处理每页数量变化
    const handleSizeChange = (size) => {
      pageSize.value = size;
      filterData.pageSize = size;
      fetchItems();
    };

    // 处理页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      filterData.page = page;
      fetchItems();
    };

    onMounted(() => {
      // 从URL参数初始化筛选条件
      if (route.query.keyword) {
        filterData.keyword = route.query.keyword;
        filters.keyword = route.query.keyword;
      }
      
      if (route.query.category) {
        const categoryId = Number(route.query.category);
        filterData.category = categoryId;
        filters.category = categoryId; // 确保同步到 filters
      }
      
      // 加载初始数据
      fetchItems();
      
      // 获取分类数据
      fetchCategories();

      console.log(
        "初始 filters.category:",
        filters.category,
        typeof filters.category
      );
    });

    return {
      items,
      total,
      loading,
      filterData,
      filters,
      fetchItems,
      handleSearch,
      handleFilterChange,
      handleTimeChange,
      resetFilters,
      categories,
      displayItems,
      showDetail,
      currentPage,
      pageSize,
      handleSizeChange,
      handleCurrentChange,
    };
  },
};
</script>

<style scoped>
.found-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: var(--text-primary);
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.items-list {
  margin-bottom: 20px;
}

.item-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.item-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.item-image {
  height: 160px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.item-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
}

.item-status.found {
  background-color: #67c23a;
}

.item-status.returned {
  background-color: #909399;
}

.item-content {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.item-content h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: var(--text-primary);
}

.item-info {
  margin-bottom: 10px;
}

.item-info p {
  display: flex;
  align-items: center;
  margin: 5px 0;
  font-size: 14px;
  color: var(--text-secondary);
}

.item-info .el-icon {
  margin-right: 5px;
  color: var(--text-secondary);
}

.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.detail-content {
  display: flex;
  gap: 20px;
}

.detail-image {
  flex: 0 0 40%;
}

.detail-image .el-image {
  width: 100%;
  height: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.detail-info {
  flex: 1;
}

.detail-info h2 {
  margin-top: 0;
  margin-bottom: 15px;
  color: var(--text-primary);
}

.item-description {
  color: var(--text-secondary);
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;  /* 限制显示2行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  max-height: 44px;  /* 根据行高调整 */
  line-height: 22px;
}

/* 添加这些额外的样式 */
:deep(.el-select) {
  width: 180px !important;
}

:deep(.el-select .el-input__inner) {
  width: 100%;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-form .el-form-item {
  margin-right: 20px;
  margin-bottom: 10px;
}

/* 确保卡片高度一致 */
.item-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.item-card .el-card__body {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.item-card .item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}
</style> 